<?php
namespace Admin\Controller;
use Admin\Logic\UsersLogic;
use Think\AjaxPage;
use Think\AjaxPage2;
use Think\Page;

class UserController extends BaseController {
	public $begin;
	public $end;
	public function _initialize(){ 
        parent::_initialize();
		$timegap = I('timegap');
		$timegap = str_replace('+',' ',$timegap);
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = $gap[0];
			$end = $gap[1];
		}else{
			$lastweek = date('Y-m-d 00:00',strtotime("-30 day"));	//30天前-1 month
			$begin = I('begin',$lastweek);
			$end =  I('end',date('Y-m-d 23:59'));
		}
		$this->begin = strtotime($begin);
		$this->end = strtotime($end);//+86399;
		$this->assign('timegap',date('Y-m-d H:i',$this->begin).' - '.date('Y-m-d H:i',$this->end));
	}
	
    public function index(){
		$this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }

    public function driver(){
        $this->assign('is_driver',1);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display('index');
    }
    /**
     * 会员列表 
     */
    public function ajaxindex(){
        // 搜索条件
        $condition = array();
		I('fenbu_id') !== '' ? $condition['fenbu_id'] = I('fenbu_id') : false;
        I('mobile') ? $condition['a.mobile'] =['like',"%".I('mobile')."%"] : false;
        I('user_id') ? $condition['a.user_id'] =['like',"%".I('user_id')."%"] : false;
        I('company_address') ? $condition['a.company_address'] =['like',"%".I('company_address')."%"] : false;
        I('email') ? $condition['email'] = I('email') : false;
        I('salesman') ? $condition['salesman'] = I('salesman') : false;
        $fast_flag=I('fast_flag');
        if($fast_flag === '0'){
            $condition['fast_flag'] = 0;
        }elseif($fast_flag == 1){
            $condition['fast_flag'] = 1;
        }
        if(!empty($_GET['is_driver'])){
            $condition['is_driver'] =$_GET['is_driver'] ;
        }
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        if($begin && $end){
            $condition['a.reg_time'] = array('between',"$begin,$end");
        }
		if(I('gouwu')==1){
			$condition['total_amount'] = 0;
		}elseif(I('gouwu')==2){
			$condition['total_amount'] = ['gt',1];
		}
		
		$nickname = trim(I('nickname'));$biaoshi = trim(I('biaoshi'));
		$nickname && !$biaoshi? $condition['_string'] =  ' (nickname like "%'.$nickname.'%") OR (company like "%'.$nickname.'%") OR (nick_name like "%'.$nickname.'%") ' :false;
		//$biaoshi ? $condition['biaoshi'] = array('like',"%$biaoshi%"): false;
		$biaoshi && !$nickname ? $condition['_string'] =  ' (biaoshi like "%'.$biaoshi.'%")  OR (biaoshi_xian ="'.$biaoshi.'") ' :false;
        if($nickname && $biaoshi){
            $condition['_string'] = '((nickname like "%'.$nickname.'%") OR (company like "%'.$nickname.'%") OR (nick_name like "%'.$nickname.'%") ) and  ((biaoshi like "%'.$biaoshi.'%")  OR (biaoshi_xian ="'.$biaoshi.'"))';
        }
        
        
        if(!empty(I('is_lock'))){
           if(I('is_lock') == 1){
                $condition['a.is_lock'] = 0;
           }else{
               $condition['a.is_lock'] = 1;
           }
        }
        $sort_order = I('order_by').' '.I('sort');
        $model = M('users a');
        $count = $model
		->where($condition)->count();
        $Page  = new AjaxPage2($count,10);
        //  搜索条件下 分页赋值 
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        
        $userList = $model
        ->field('a.*,(select count(*) from ty_users c where c.parent_id=a.user_id) as xiaxian')
        ->where($condition)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
         foreach($userList as $key=>$v){
             $sameOrder = M('order')->where(['user_id'=>$v['user_id'],'order_status'=>['in','0,1,2']])->order('order_id asc')->getField('same_order');
            //  dump($sameOrder);
             $userList[$key]['price'] = M('order')->where(['user_id'=>$v['user_id'],'order_status'=>['in','0,1,2'],'sameOrder'=>$sameOrder])->order('order_id asc')->sum('total_amount');
            //  dump($userList[$key]['price']);
             //首单金额处理
             //获取用户第一次下单的时间
             $first_date = M('order')->where(['user_id'=>$v['user_id'],'order_status'=>['in','0,1,2']])->order('add_time asc')->limit(1)->getField('add_time');
             //获取用户第一次下单的当天的所有订单
             $first_order_amount = 0;
             if ($first_date){
                 $today = date('Y-m-d',$first_date);
                 $todayStart = strtotime($today);
                 $todayEnd = strtotime($today . ' 23:59:59');
                 $first_order_amount = M('order')
                     ->where(['add_time'=>['between',"$todayStart,$todayEnd"],'order_status'=>['in','0,1,2'],'user_id'=>$v['user_id']])
                     ->sum('order_amount');

             }
             $userList[$key]['first_order_amount'] = $first_order_amount;


			 $userList[$key]['parent_name']=M('users')->where('user_id='.$v['parent_id'])->getField('company');
 			 $userList[$key]['province'] = M('region')->where(['id'=>$v['province_id']])->getField('name');
			 $userList[$key]['city'] = M('region')->where(['id'=>$v['city_id']])->getField('name');
			 $userList[$key]['disti'] = M('region')->where(['id'=>$v['distinguish_id']])->getField('name');
			 $userList[$key]['street'] = M('region')->where(['id'=>$v['street_id']])->getField('name');
         }
        $user_id_arr = get_arr_column($userList, 'user_id');
        if(!empty($user_id_arr))
        {
            $first_leader = M('users')->query("select first_leader,count(1) as count  from __PREFIX__users where first_leader in(".  implode(',', $user_id_arr).")  group by first_leader");
            $first_leader = convert_arr_key($first_leader,'first_leader');
            
            $second_leader = M('users')->query("select second_leader,count(1) as count  from __PREFIX__users where second_leader in(".  implode(',', $user_id_arr).")  group by second_leader");
            $second_leader = convert_arr_key($second_leader,'second_leader');
            
            $third_leader = M('users')->query("select third_leader,count(1) as count  from __PREFIX__users where third_leader in(".  implode(',', $user_id_arr).")  group by third_leader");
            $third_leader = convert_arr_key($third_leader,'third_leader');
        }
        $this->assign('first_leader',$first_leader);
        $this->assign('second_leader',$second_leader);
        $this->assign('third_leader',$third_leader);

        $show = $Page->show();
        $this->assign('userList',$userList);
		$this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('level',M('user_level')->getField('level_id,level_name'));
        $this->display();
    }

//下线详情 
    public function xiaxians() 
    {
		$user_id= I('user_id');
        $model = M("users a");
        $where = "a.parent_id = ".$user_id; //." and a.reg_time>=".$this->begin." and a.reg_time<=".$this->end;
		$user_name=I('user_name');
		if($user_name){
			$where .= " and (a.company like '%".$user_name."%' or a.nick_name like '%".$user_name."%')";
		}

        $count = $model
		->field('a.*,b.store_name')
		->join('ty_store b on a.store_id=b.store_id','LEFT')
		->where($where)->select();
			
        $Page  = new Page(count($count),20);
        $list = $model
		->field('a.*,b.store_name,
		(select sum(order_amount) from ty_order b where b.user_id=a.user_id and b.add_time>='.$this->begin.' and b.add_time<='.$this->end.') as xiadan,
		(select count(*) from ty_users c where c.parent_id=a.user_id) as xiaxian')
		->join('ty_store b on a.store_id=b.store_id','LEFT')
		->where($where)->order("xiadan desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
        $this->assign('show',$show);
		$this->assign('heji',count($count));
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	}
	
	public function export_xians()
	{
		//搜索条件
		$user_id= I('user_id');
        $model = M("users a");
        $where = "a.parent_id = ".$user_id; //." and a.reg_time>=".$this->begin." and a.reg_time<=".$this->end;
		$user_name=I('user_name');
		if($user_name){
			$where .= " and (a.company like '%".$user_name."%' or a.nick_name like '%".$user_name."%')";
		}

        $list = $model
		->field('a.*,b.store_name,
		(select sum(order_amount) from ty_order b where b.user_id=a.user_id and b.add_time>='.$this->begin.' and b.add_time<='.$this->end.') as xiadan,
		(select count(*) from ty_users c where c.parent_id=a.user_id) as xiaxian')
		->join('ty_store b on a.store_id=b.store_id','LEFT')
		->where($where)->order("xiadan desc")->select();
	             
		$strTable ='<table width="500" border="1">';
		$strTable .= '<tr>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="160">会员昵称</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">公司/姓名</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">累积消费</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">下线数</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册日期</td>';
		$strTable .= '</tr>';
		
		foreach($list as $k=>$val){
			$strTable .= '<tr>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['user_id'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['nick_name'].' </td>';
	        $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company'].'</td>';
	        $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['xiadan'].' </td>';
	            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['xiaxian'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['mobile'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.date("Y-m-d H:i:s",$val['reg_time']).'</td>';
			$strTable .= '</tr>';
		}
		$strTable .='</table>';
		unset($list);
		downloadExcel($strTable,'下线导出');
		exit();
	}

    /**
     * 会员详细信息查看
     */
    public function detail(){
        $uid = I('get.id');
        $user = D('users')->where(array('user_id'=>$uid))->find();
        if(!$user)
            exit($this->error('会员不存在'));
        if(IS_POST){ 
            //  会员信息编辑
            $company = I('post.company');
            $company_address = I('post.company_address');
            $password = I('post.password');
            if($password){
                $_POST['password'] = encrypt($password);
            }else{
                unset($_POST['password']);
            }
            $row = M('users')->where(array('user_id'=>$uid))->save($_POST);
            if($row)
                exit($this->success('修改成功'));
            exit($this->error('未作内容修改或修改失败'));
        }
        
        $user['first_lower'] = M('users')->where("first_leader = {$user['user_id']}")->count();
        $user['second_lower'] = M('users')->where("second_leader = {$user['user_id']}")->count();
        $user['third_lower'] = M('users')->where("third_leader = {$user['user_id']}")->count();

        $level = M('user_level')->where(['fenbu_id'=>$user['fenbu_id']])->select();
        $this->assign('level',$level);
        $this->assign('user',$user);
		$this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    
    
    public function add_user(){
    	if(IS_POST){
    		$data = I('post.');
    		$user_obj = new UsersLogic();
    		$res = $user_obj->addUser($data);
    		if($res['status'] == 1){
    			$this->success('添加成功',U('User/index'));exit;
    		}else{
    			$this->error('添加失败,'.$res['msg'],U('User/index'));
    		}
    	}
    	$this->display();
    }

    /**
     * 用户收货地址查看
     */
    public function address(){
        $uid = I('get.id');
        $lists = D('user_address')->where(array('user_id'=>$uid))->select();
        $regionList = M('Region')->getField('id,name');
        $this->assign('regionList',$regionList);
        $this->assign('lists',$lists);
        $this->display();
    }

    /**
     * 删除会员
     */
    public function delete(){
        $uid = I('get.id');
		$order_pd=M('order')->where('user_id='.$uid.' and order_status in(0,1,2)')->find();
		$seller_pd=M('store')->where('user_id='.$uid.' and store_state=1')->find();
		if($order_pd){
			$this->error('该会员已经购物，禁止删除！');
			exit;
		}elseif($seller_pd){
			$this->error('该会员店铺还未关闭，禁止删除！');
			exit;
		}else{
			 M('users')->where(array('user_id'=>$uid))->delete();$this->success('成功删除会员');
		}
    }

    /**

     * 批量删除会员

     */

    public function  batch_delete(){
        $id = I('get.id');

        $id = ltrim($id,",");

        $row = M('users')->delete($id);


        if ($row){
                $res = array('status'=>1,"msg"=>"删除成功!");
            $jsonencode = json_encode($res);
            echo $jsonencode;
            exit;

            }else{
                $res = array('status'=>0,"msg"=>"删除失败!");
            $jsonencode = json_encode($res);
            echo $jsonencode;
            exit;

        }

    }


    /**

     * 账户资金记录
     */
    public function account_log(){
        $user_id = I('get.id');
        //获取类型
        $type = I('get.type');
        //获取记录总数
        $count = M('account_log')->where(array('user_id'=>$user_id))->count();
        $page = new Page($count);
        $lists  = M('account_log')->where(array('user_id'=>$user_id))->order('change_time desc')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('user_id',$user_id);
        $this->assign('page',$page->show());
        $this->assign('lists',$lists);
        $this->display();
    }

    /**
     * 账户资金调节
     */
    public function account_edit(){
        $user_id = I('get.id');
        if(!$user_id > 0)
            $this->error("参数有误");
        if(IS_POST){
            //获取操作类型
            $m_op_type = I('post.money_act_type');
            $user_money = I('post.user_money');
            $user_money =  $m_op_type ? $user_money : 0-$user_money;

            $p_op_type = I('post.point_act_type');
            $pay_points = I('post.pay_points');
            $pay_points =  $p_op_type ? $pay_points : 0-$pay_points;

            $f_op_type = I('post.frozen_act_type');
            $frozen_money = I('post.frozen_money');
            $frozen_money =  $f_op_type ? $frozen_money : 0-$frozen_money;

            $desc = I('post.desc');
            if(!$desc)
                $this->error("请填写操作说明");
            if(accountLog($user_id,$user_money,$pay_points,$desc)){
                $this->success("操作成功",U("Admin/User/account_log",array('id'=>$user_id)));
            }else{
                $this->error("操作失败");
            }
            exit;
        }
        $this->assign('user_id',$user_id);
        $this->display();
    }
    
    public function recharge(){
        $timegap = I('timegap');
    	$nickname = I('nickname');
    	$map = array();
    	if($timegap){
    		$gap = explode(' - ', $timegap);
    		$begin = $gap[0];
    		$end = $gap[1];
    		$map['ctime'] = array('between',array(strtotime($begin),strtotime($end)));
    	}
    	if($nickname){
    		$map['nickname'] = array('like',"%$nickname%");
    	}  
    	$count = M('recharge')->where($map)->count();
    	$page = new Page($count);
    	$lists  = M('recharge')->where($map)->order('ctime desc')->limit($page->firstRow.','.$page->listRows)->select();
    	$this->assign('page',$page->show());
    	$this->assign('lists',$lists);
    	$this->display();
    }
    
    public function level(){
    	$act = I('GET.act','add');
    	$this->assign('act',$act);
    	$level_id = I('GET.level_id');
    	$level_info = array();
    	if($level_id){
    		$level_info = D('user_level')->where('level_id='.$level_id)->find();
    		$this->assign('info',$level_info);
    	}
    	$this->display();
    }
    
    public function levelList(){
    	$Ad =  M('user_level');
    	$res = $Ad->where('1=1')->order('level_id')->page($_GET['p'].',10')->select();
    	if($res){
    		foreach ($res as $val){
    			$list[] = $val;
    		}
    	}
    	$this->assign('list',$list);
    	$count = $Ad->where('1=1')->count();
    	$Page = new \Think\Page($count,10);
    	$show = $Page->show();
    	$this->assign('page',$show);
    	$this->display();
    }
	
	public function tousu(){
		$tousu =  M('tousu a');
		$list = $tousu
		->field('a.*,b.company,b.nickname,b.mobile')
		->join('ty_users b on a.user_id=b.user_id')
		->where('1=1')->order('tousu_id desc')->page($_GET['p'].',10')->select();

		$this->assign('list',$list);
		$count = $tousu->where('1=1')->count();
		$Page = new \Think\Page($count,10);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->display();
	}
    
    public function levelHandle(){
    	$data = I('post.');
    	if($data['act'] == 'add'){
    		$r = D('user_level')->add($data);
    	}
    	if($data['act'] == 'edit'){
    		$r = D('user_level')->where('level_id='.$data['level_id'])->save($data);
    	}
    	 
    	if($data['act'] == 'del'){
    		$r = D('user_level')->where('level_id='.$data['level_id'])->delete();
    		if($r) exit(json_encode(1));
    	}
    	 
    	if($r){
    		$this->success("操作成功",U('Admin/User/levelList'));
    	}else{
    		$this->error("操作失败",U('Admin/User/levelList'));
    	}
    }

    /**
     * 搜索用户名
     */
    public function search_user()
    {
        $search_key = trim(I('search_key'));        
        if(strstr($search_key,'@'))    
        {
            $list = M('users')->where(" email like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "<option value='{$val['user_id']}'>{$val['email']}</option>";
            }                        
        }
        else
        {
            $list = M('users')->where(" mobile like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
            }            
        } 
        exit;
    }
    
    /**
     * 分销树状关系
     */
    public function ajax_distribut_tree()
    {
          $list = M('users')->where("first_leader = 1")->select();
          $this->display();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users', $users);
        $this->display();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function save_user()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        //获取分部
        $fenbu = M('fenbu')->select();
        $this->assign('users', $users);
        $this->assign('fenbu', $fenbu);
        $this->display();
    }

    /**
     * 修改用户线路或者是否快线
     * */
    public function doSaveUser(){
        $call_back = I('call_back');//回调方法
        $type = I('type');
        $users = I('post.user');
        $content = I('post.content');
        $fenbu_id = I('post.fenbu_id');
        if(!empty($users)){
            $user_id_array = implode(',', $users);
        }
        if($type == 0){
            //批量修改线路
            $user = M('users')->where(['user_id'=>['in',$user_id_array]])->save(['biaoshi_xian'=>$content]);
        }elseif($type == 1){
            // $userList = M('users')->where(['user_id'=>['in',$user_id_array]])->select();
            // foreach ($userList as $k=>$v){
            //     if($v['fast_flag'] == 1){
            //         M('users')->where(['user_id'=>$v['user_id']])->save(['fast_flag'=>0]);
            //     }else{
            //         M('users')->where(['user_id'=>$v['user_id']])->save(['fast_flag'=>1]);
            //     }
            // }
            $user = M('users')->where(['user_id'=>['in',$user_id_array]])->save(['fast_flag'=>1]);
        }elseif($type == 2){
             $user = M('users')->where(['user_id'=>['in',$user_id_array]])->save(['fenbu_id'=>$fenbu_id]);
        }elseif($type == 3){
             $user = M('users')->where(['user_id'=>['in',$user_id_array]])->save(['fast_flag'=>0]);
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }

    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage()
    {
        $call_back = I('call_back');//回调方法
        $message = I('post.text');//内容
        $type = I('post.type', 0);//个体or全体
        $admin_id = session('admin_id');
        $users = I('post.user');//个体id
        $message = array(
            'admin_id' => $admin_id,
            'message' => $message,
            'category' => 0,
            'send_time' => time()
        );
        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            M('Message')->data($message)->add();
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = M('Message')->data($message)->add();
                foreach ($users as $key) {
                    M('user_message')->data(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0))->add();
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }

    /**
     *
     * @time 2016/09/03
     * @author dyr
     * 发送邮件
     */
    public function sendMail()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $user_where = array(
                'user_id' => array('IN', $user_id_array),
                'email'=> array('neq','')
            );
            $users = M('users')->field('user_id,nickname,email')->where($user_where)->select();
        }
        $this->assign('smtp',tpCache('smtp'));
        $this->assign('users',$users);
        $this->display();
    }

    /**
     * 发送邮箱
     * @author dyr
     * @time  2016/09/03
     */
    public function doSendMail()
    {
        $call_back = I('call_back');//回调方法
        $message = I('post.text');//内容
        $title = I('post.title');//标题
        $users = I('post.user');
        if (!empty($users)) {
            $user_id_array = implode(',', $users);
            $users = M('users')->field('email')->where(array('user_id' => array('IN', $user_id_array)))->select();
            $to = array();
            foreach ($users as $user) {
                if (check_email($user['email'])) {
                    $to[] = $user['email'];
                }
            }
            $res = send_email($to, $title, $message);
            echo "<script>parent.{$call_back}({$res});</script>";
            exit();
        }
    }
	
    public function export_user()
    {
		I('mobile') ? $condition['mobile'] = I('mobile') : false;
		$nickname = trim(I('nickname'));$biaoshi = trim(I('biaoshi'));
		$nickname ? $condition['_string'] =  ' (nickname like "%'.$nickname.'%")  OR (company like "%'.$nickname.'%") ' :false;
//		if(I('gouwu')==1){
//			$condition['total_amount'] = 0;
//		}elseif(I('gouwu')==2){
//			$condition['total_amount'] = ['gt',1];
//		}
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        if($begin && $end){
            $condition['a.reg_time'] = array('between',"$begin,$end");
        }
		$biaoshi ? $condition['_string'] =  ' (biaoshi ="'.$biaoshi.'")  OR (biaoshi_xian = "'.$biaoshi.'") ' :false;
		$orderList =M('users a')
		->field('a.user_id,a.total_amount,a.parent_id,a.nick_name,a.nickname,a.mobile,a.is_lock,a.biaoshi,a.biaoshi_xian,a.xsort,a.reg_time,a.company_address,a.fast_flag,a.company,b.fenbu_name')
        ->join('ty_fenbu b ON a.fenbu_id = b.fenbu_id')
		->where($condition)->select();
    	//$orderList = D()->query('select a.user_id,a.nick_name,a.nickname,a.mobile,a.biaoshi,a.reg_time,a.company_address,a.company,(select count(*) from ty_order b where b.user_id=a.user_id) as orpd from __PREFIX__users a');

    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">用户ID</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="100">昵称</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">姓名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">标识</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路排序</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">所属分部</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">公司/店铺</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">地址</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">启用</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否有下单</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">末单金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">末单时间</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">下单总金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">上级推荐人</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册时间</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否快线</td>';
    	$strTable .= '</tr>';
    	foreach($orderList as $k=>$val){
		$is_lock=($val['is_lock']==0) ? "启用" : "禁用";
		    $order = M('order')->where(['user_id'=>$val['user_id'],'order_status'=>['in','0,1,2']])->order('order_id desc')->find();
		    if(!empty($order)){
		        $title = '是';
		        $oneTime = date('Y-m-d H:i:s',$order['add_time']);
		        $price = $order['total_amount'];
            }else{
                $title = '否';
                $oneTime = '';
                $price = 0;
            }
            if($val['parent_id'] != 0){
                $parentUser = M('users')->where(['user_id'=>$val['parent_id']])->find();
                if(!empty($parentUser)){
                    $parentName = $parentUser['user_id'].'-'.$parentUser['company'];
                }else{
                    $parentName = '';
                }
            }else{
                $parentName = '';
            }
            if($val['fast_flag'] == 1){
                $fast_flag = '是';
            }else{
                $fast_flag = '否';
            }
            $zong = M('order')->where(['user_id'=>$val['user_id'],'order_status'=>['in','0,1,2']])->sum('total_amount');
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['user_id'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nick_name'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['nickname'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['biaoshi'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['biaoshi_xian'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['xsort'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['fenbu_name'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company_address'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$is_lock.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$title.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$price.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$oneTime.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$zong.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$parentName.'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val['reg_time']).'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$fast_flag.'</td>';
    		$strTable .= '</tr>';//ob_start(); 
			//$len1=ob_get_length();
    	}
		
		//echo $len1;exit;
    	$strTable .='</table>';
    	unset($orderList);
		header('Content-Type:application/vnd.ms-excel');
		Header("Accept-Ranges:bytes");
		header("Content-Type: application/force-download");
		header("Content-Disposition: attachment; filename=users_".date('Y-m-d').".xls");
		header('Expires:0');
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
		header("Pragma: no-cache"); 
		header('Pragma:public');
		header('Cache-Control: max-age=0');
		echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$strTable.'</html>';
    	downloadExcel($strTable,'users');
    	exit();
    }
	public function quyu_sousuo(){
		$key=I('key');
		if($key){
		$fenlei=M('users')
		->field('user_id,company,mobile')
		->where('company like "%'.$key.'%" or mobile like"%'.$key.'%"')->limit(15)->select();
		
		echo '<li rev="0,0,0" style="color:red">清理推荐人</li>';
		foreach($fenlei as $v){
				echo '<li rev="'.$v['user_id'].','.$v['company'].','.$v['mobile'].'">'.$v['company'].'</li>';
		}
		}
		exit;
	}
	
	public function quyu_edit(){
		$id=I('id');$parent_id=I('parent_id');
		if($id){
			M('users')->where('user_id='.$id)->setField('parent_id',$parent_id);
		}
		exit;
	}
	
}